﻿using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FGrubert.CrmQueueMonitor.WinForms
{
    /// <summary>
    /// Helper class to create a CRM connection
    /// </summary>
    public static class CrmConnector
    {
        /// <summary>
        /// Creates a new crm connection
        /// </summary>
        /// <param name="settings">Settings object with the saved settings</param>
        /// <returns>An organization service</returns>
        internal static IOrganizationService GetCrmConnection(Properties.Settings settings)
        {
            return GetCrmConnection(new Uri(settings.CrmUrl), settings.UseIntegratedAuthentication, settings.Domain, settings.Username, settings.Password);
        }

        /// <summary>
        /// Creates a new crm connection
        /// </summary>
        /// <param name="crmUrl">The URI to the CRM System</param>
        /// <param name="useIntegratedAuthentication">If the intergrated credentials should be used</param>
        /// <param name="domain">The domain of the user (if not integrated)</param>
        /// <param name="username">The username of the user (if not integrated)</param>
        /// <param name="password">The password of the user (if not integrated)</param>
        /// <returns>An organization service</returns>
        internal static IOrganizationService GetCrmConnection(Uri crmUrl, bool useIntegratedAuthentication, string domain, string username, string password)
        {
            CrmConnection connection = null;

            if (useIntegratedAuthentication)
            {
                string connectionString = string.Format("Url={0};", crmUrl);
                connection = CrmConnection.Parse(connectionString);
            }
            else
            {
                string connectionString = string.Format("Url={0}; Domain={1}; Username={2}; Password={3}", crmUrl, domain, username, password);
                connection = CrmConnection.Parse(connectionString);
            }

            OrganizationService orgService = new OrganizationService(connection);

            WhoAmIRequest request = new WhoAmIRequest();
            WhoAmIResponse response = (WhoAmIResponse)orgService.Execute(request);

            return orgService;
        }

        /// <summary>
        /// Retrieve the CRM Version
        /// </summary>
        /// <param name="orgService">The organization service</param>
        /// <returns>The version of the CRM Service</returns>
        internal static CrmVersion GetCrmVersion(IOrganizationService orgService)
        {
            RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
            RetrieveVersionResponse versionResponse = (RetrieveVersionResponse)orgService.Execute(versionRequest);

            CrmVersion version = CrmVersion.Unknown;

            string mainVersionString = versionResponse.Version.Substring(0, versionResponse.Version.IndexOf('.'));
            int mainVersion = Int32.Parse(mainVersionString);

            if (mainVersion == 5)
            {
                version = CrmVersion.Crm2011;
            }
            else if (mainVersion == 6)
            {
                version = CrmVersion.Crm2013;
            }
            else if(mainVersion > 6)
            {
                version = CrmVersion.After2013;
            }
            return version;
        }
    }
}
